#!/bin/bash

APP=gmall

# 判断日期参数，日期参数是第二个参数
if [ -n "$2" ]; then
    do_date=$2
else
    echo "请传入日期参数"
    exit
fi

common_sql="use ${APP};"

dws_trade_user_order_td_sql="
    insert overwrite table dws_trade_user_order_td partition (dt = '${do_date}')
    select
        user_id,
        min(dt) order_date_first,
        max(dt) order_date_last,
        sum(order_count_1d) order_count_td,
        sum(order_num_1d) order_num_td,
        sum(order_original_amount_1d) original_amount_td,
        sum(activity_reduce_amount_1d) activity_reduce_amount_td,
        sum(coupon_reduce_amount_1d) coupon_reduce_amount_td,
        sum(order_total_amount_1d) total_amount_td
    from dws_trade_user_order_1d
    where dt <= '${do_date}'
    group by user_id;
"

dws_user_user_login_td_sql="
    with full_user as (
        select
            id user_id,
            date_format(create_time, 'yyyy-MM-dd') date_id
        from dim_user_zip
        where dt = '9999-12-31' and date_format(create_time, 'yyyy-MM-dd') <= '${do_date}'
    ), login_info as (
        select
            user_id,
            date_id
        from dwd_user_login_inc
        where dt = '${do_date}'
    ), full_login_info as (
        select * from full_user
        union all
        select * from login_info
    )
    insert overwrite table dws_user_user_login_td partition (dt = '${do_date}')
    select
        user_id,
        max(date_id) login_last_date,
        count(1) login_count_td
    from full_login_info
    group by user_id;
"

# 判断表名参数，表名参数是第一个参数
case $1 in
"dws_trade_user_order_td")
    hive -e "${common_sql}${dws_trade_user_order_td_sql}"
;;
"dws_user_user_login_td")
    hive -e "${common_sql}${dws_user_user_login_td_sql}"
;;
"all")
    hive -e "${common_sql}${dws_trade_user_order_td_sql}${dws_user_user_login_td_sql}"
;;
esac